package com.bw.controller;

import com.bw.domain.Role;
import com.bw.domain.TbMenu;
import com.bw.domain.User;
import com.bw.service.UserService;
import com.bw.utils.CheckUtil;
import com.bw.utils.MailUtil;
import com.bw.utils.MenuUtil;
import com.bw.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: TaoShiHao
 * @Date: 2025/3/12 15:11
 * @Description:
 * 登录模块
 **/
@Controller
@RequestMapping("auth")
public class AuthController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    int count=5;
    @RequestMapping("tologin")
    public String tologin(){
        return "login";
    }
    @ResponseBody
    @RequestMapping("login")
    public R login(String username, String password, HttpSession session){

        //失败次数
        String failCount="failCount"+username;
        //锁定用户
        String failLock="failLock"+username;
        Object userLock = redisTemplate.opsForValue().get(failLock);
        if(userLock!=null){
            return R.ERROR(500,"账号已被锁定,请五分钟后再试");
        }
        User user=userService.login(username);
        if(username==null||username.length()<8){
            return R.ERROR(500,"用户名不能为空并且长度不能小于8位");
        }
        if(password==null||password.length()<6){
            return R.ERROR(500,"密码不能为空并且长度不能小于6位");
        }
        if(!CheckUtil.mustNumAndLetter(password)){
            return R.ERROR(500,"密码必须包含字母和数字");
        }
        if(user==null){
            return R.ERROR(500,"用户不存在");
        }
        if(!user.getPassword().equals(password)){
            Long num = redisTemplate.opsForValue().increment(failCount);
            if(num>=count){
                redisTemplate.opsForValue().set(failLock,1,5, TimeUnit.MINUTES);
                redisTemplate.delete(failCount);
                return R.ERROR(500,"密码错误次数过多,请稍后再试");
            }
            return R.ERROR(500,"密码错误,还有"+(count-num)+"次机会");

        }
//        6.登录成功后将用户信息、用户角色、权限信息等存放到缓存中
        redisTemplate.opsForValue().set("user:"+user.getId(),user);
        //查询用户角色
         List<Role> roleList=userService.listRoleByUserId(user.getId());
        redisTemplate.opsForValue().set("role:"+user.getId(),roleList);
        //查询用户的权限
        List<TbMenu> tbMenuList=userService.listMenuByUserId(user.getId());
        List<TbMenu> menuList = MenuUtil.treeMenus(tbMenuList, null);
        redisTemplate.opsForValue().set("menu:"+user.getId(),menuList);
        session.setAttribute("user",user);
        return R.OK();
    }
}
